package com.snail.auth.controller;

import com.snail.auth.form.LoginBody;
import com.snail.auth.form.RegisterBody;
import com.snail.auth.service.SysLoginService;
import com.snail.common.core.domain.R;
import com.snail.common.core.utils.JwtUtils;
import com.snail.common.core.utils.StringUtils;
import com.snail.common.security.auth.AuthUtil;
import com.snail.common.security.service.TokenService;
import com.snail.common.security.utils.SecurityUtils;
import com.snail.system.api.dto.SysTenantDto;
import com.snail.system.api.model.LoginUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * token 控制
 *
 * @author snail
 */
@Api(value = "登录管理", tags = "登录管理")
@RestController
public class TokenController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @ApiOperation(value = "登录")
    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form);
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    @ApiOperation(value = "发送验证码")
    @GetMapping("/sendCode/{phone}")
    public R<?> smsCode(@PathVariable("phone") String phone) {
        // 获取登录token
        return R.ok(sysLoginService.sendSmsCode(phone));
    }

    @ApiOperation(value = "退出")
    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @ApiOperation(value = "刷新token")
    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @ApiOperation(value = "注册")
    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody) {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }

    @ApiOperation(value = "获取租户")
    @GetMapping("/tenant")
    public R<List<SysTenantDto>> getTenant() {
        return R.ok(sysLoginService.getTenant());
    }
}
